<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编码" prop="orderNumber" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="司机姓名" prop="driverName" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入司机姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="买家姓名" prop="buyerName" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.buyerName"
          placeholder="请输入买家姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="vehicleType" style="margin-right: 20px;margin-bottom: 30px;" :label-width="'150px'">
        <el-select v-model="queryParams.vehicleType" placeholder="订单状态" clearable>
          <el-option
            v-for="dict in dict.type.lg_vehicle_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="签收状态" prop="isCompleted" style="margin-right: 30px;margin-bottom: 30px;">
        <el-select v-model="queryParams.isCompleted" placeholder="订单状态" clearable>
          <el-option
            v-for="dict in dict.type.lg_qianshou_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" style="margin-right: 30px;margin-bottom: 30px;margin-bottom: 30px;">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['outorder:every:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['caroutorder:every:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['caroutorder:every:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['outorder:every:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="everyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column label="司机联系方式" align="center" prop="driverPhone" />
      <el-table-column label="车辆类型" align="center" prop="coldId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lg_vehicle_type" :value="scope.row.coldId"/>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" prop="licensePlate" />
      <el-table-column label="买家姓名" align="center" prop="buyerName" />
      <el-table-column label="电话" align="center" prop="buyerPhone" />
      <el-table-column label="最低温度" align="center" prop="deliveryMin">
        <template slot-scope="scope">
          {{ scope.row.deliveryMin }} ℃
        </template>
      </el-table-column>
      <el-table-column label="最高温度" align="center" prop="deliveryMax">
        <template slot-scope="scope">
          {{ scope.row.deliveryMax }} ℃
        </template>
      </el-table-column>
      <el-table-column label="签收状态" align="center" prop="isCompleted">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lg_qianshou_type" :value="scope.row.isCompleted"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200" align="center" prop="createTime" />
      <el-table-column label="操作" align="center"  width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['outorder:every:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['outorder:every:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />



    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNumber">
              <el-input v-model="form.orderNumber" placeholder="请输入订单编号" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="form.driverName" placeholder="请输入司机姓名"  :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="司机联系方式" prop="driverPhone">
              <el-input v-model="form.driverPhone" placeholder="请输入司机联系方式" :disabled="isEdit" />
            </el-form-item>
          </el-col>



          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-model="form.licensePlate" placeholder="请输入车牌号" :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="买家姓名" prop="buyerName">
              <el-input v-model="form.buyerName" placeholder="请输入买家姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="买家电话" prop="buyerPhone">
              <el-input v-model="form.buyerPhone" placeholder="请输入买家电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">

          <el-col :span="6">
            <el-form-item label="最低温度" prop="deliveryMin">
              <el-input v-model="form.deliveryMin" placeholder="请输入最低温度" :disabled="isEdit">
                <template slot="append">℃</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最高温度" prop="deliveryMax">
              <el-input v-model="form.deliveryMax" placeholder="请输入最高温度" :disabled="isEdit">
                <template slot="append">℃</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="coldId" >
              <el-radio-group v-model="form.coldId">
                <el-radio v-for="dict in dict.type.lg_vehicle_type" :key="dict.value" :label="dict.value" :disabled="isEdit">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="签收状态" prop="isCompleted">
              <el-radio-group v-model="form.isCompleted">
                <el-radio v-for="dict in dict.type.lg_qianshou_type" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>

import { listbill, getBillById, updateBill, geUnitType, addBill,delBill,getWarehouseType } from '@/api/order/carorder'
import store from "@/store";
export default {
  name: "Bill",
  dicts: ['lg_vehicle_type','lg_qianshou_type'],
  data() {
    return {
      // 遮罩层
      userId:store.state.user.id, //将缓存的用户id赋值给userId
      userName:store.state.user.name, //将缓存的用户id赋值给userId
      loading: true,
      dateRange:[],
      vehicleType : null,
      // 选中数组
      ids: [],
      // 初始化价格区间数组，最小值为0，最大值为空
      priceRange: [null, null],
      // 非单个禁用
      single: true,
      selectedOrderNumber: null, // 记录当前订单编号
      buyName:null,
      buyPhone:null,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showDriverListDialog: false, // 控制弹窗显示
      showDetailDialog : false,
      showCar: false,
      //选冷库区域
      warehouseDialogVisible: false, // 仓库选择对话框
      warehouseList: [], // 存储冷库数据
      selectedWarehouse: null, // 选中的仓库
      selectedRow: null, //存储订单行
      // 总条数
      total: 0,
      dialogVisible: false,   // 控制弹出框的显示与隐藏
      currentImage: '',       // 当前要放大的图片的 URL
      // 岗位表格数据
      everyList: [],
      driverList: [],
      carList : [],
      detail: {},
      //到时候要调接口
      goodsUnit: [],
      goodsName: [
        { id: 1, name: '蔬菜' },
        { id: 2, name: '水果' }
      ],
      goodsNameOptions:[],
      //类型
      cktype:[
        { id: 1, name: '常温' },
        { id: 2, name: '冷冻' }
      ],
      warehouseTypes:[],
      goodsUnitOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehicleType : null,
        buyerName : null,
        createTime: null,
        orderNumber : null,
        driverName : null,
        isCompleted: null,
      },
      // 表单参数
      form: {
        warehouseId: "", // 选中的冷库 ID
        subWarehouseId: "", // 选中的子冷库 ID
        warehouseName: "", // 冷库名称
        subWarehouseName: "", // 子冷库名称
        cktype: null, // 绑定的值应为 id
        goodsNameUnits:null,
      },
      rules: {
        orderNumber: [
          {required: true, message: "订单编号不能为空", trigger: "blur"}
        ],
        buyerName: [
          {required: true, message: "买家姓名不能为空", trigger: "blur"}
        ],
        buyerPhone: [
          {required: true, message: "买家手机号不能为空", trigger: "blur"}
        ],

        isCompleted: [
          {required: true, message: "签收状态", trigger: "blur"}
        ],
      }

    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 打开弹出框并显示点击的图片
    openDialog(imageType) {
      if (imageType === 'customerSign') {
        this.currentImage = this.detail.customerSign; // 获取客户签字图片链接
      } else if (imageType === 'buyerSign') {
        this.currentImage = this.detail.buyerSign; // 获取买家签字图片链接
      }
      this.dialogVisible = true;  // 显示弹出框
    },
    // 关闭弹出框
    closeDialog() {
      this.dialogVisible = false;  // 隐藏弹出框
    },

    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listbill(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.everyList = response.rows;
          this.total = response.total;
          this.loading = false;
      });

    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = Object.assign({}, {
        orderNumber: null,
        sellerName: null,
        goodsName: null,
        cktype: null,
        needVehicle: null,
        orderStatus: null,

        priceRange: [null, null]
      });

      this.resetForm("form");
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
      if (selection.length > 0) {
        this.selectedWarehouse = selection[0]; // 只取第一个选中的
      } else {
        this.selectedWarehouse = null;
        this.selectedRow = null;
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
              this.form.createBy=this.userName,
              this.form.updateBy=this.userName,
            //   this.form.cktype = parseInt(this.form.cktype);
            // this.form.goodsName = parseInt(this.form.goodsName);
            updateBill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBill(this.form).then(response => {
              this.form.createBy=this.userName,
                this.form.updateBy=this.userName,
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

// // 查看详情
//     handlexq(row){
//       this.showDetailDialog=true;
//       const billId = row.id || this.ids
//       getBillById(billId).then(response => {
//         this.detail = response.data;
//         // 这里转换 goodsUnit 为中文名称
//         const unit = this.goodsUnit.find(unit => unit.id === Number(this.detail.goodsUnit));
//         this.detail.goodsUnit = unit ? unit.unitName : "未知单位";
//       });
//
//     },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isEdit = false;
      this.goodsNameOptions = this.goodsName;
      this.goodsUnitOptions = this.goodsUnit;
      this.warehouseTypes=this.cktype;
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // console.log("row"+row.id)
      this.reset();
      this.isEdit = true;
      // this.goodsUnitOptions = this.goodsUnit;
      // this.warehouseTypes=this.cktype;
      // this.goodsNameOptions = this.goodsName;

      const billId = row.id || this.ids
      getBillById(billId).then(response => {
        this.form = response.data;

        // // 确保 goodsUnit 是数字类型
        // this.form.goodsUnit = Number(response.data.goodsUnit);
        this.form.coldId= String(response.data.coldId);
        this.form.isCompleted= String(response.data.isCompleted);
        this.open = true;
        this.title = "修改订单";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const billIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + billIds + '"的数据项？').then(function() {
        return delBill(billIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('content/bill/export', {
        ...this.queryParams
      }, `bill_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
